import axios from 'axios'
import { router } from '../router'
import store from '../store'
import Vue from 'vue'
import Cookies from 'js-cookie'
const EventBus = new Vue()

const host = global_config.BASE_URL

const api = host + '/backend'
const $http = axios.create({
  baseURL: api,
  timeout: 30000,
  withCredentials: true
})
// 添加请求拦截器
$http.interceptors.request.use(config => {
   return config
})
// 添加响应拦截器
$http.interceptors.response.use(
  res => {
    let { code, data, msg } = res.data
    if (code == 500) {
      EventBus.$Message.error(msg + '')
    } else if (code == 10000) {
      if (router.currentRoute.query.redirect) {
        return { data: null }
      }
      store.commit('logout', this)
      store.commit('clearOpenedSubmenu')
      router.replace({
        name: 'login',
        query: { redirect: router.currentRoute.fullPath }
      })
    }
    return res.data
  },
  error => {
    console.log(error)
    var originalRequest = error.config
    if (
      error.code == 'ECONNABORTED' &&
      error.message.indexOf('timeout') != -1 &&
      !originalRequest._retry
    ) {
      router.push({
        name: 'error-500'
      })
      return
    }
    if (error.response) {
      if (error.response.status === 403) {
        router.push({
          name: 'error-403'
        })
      }
      if (error.response.status === 500) {
        router.push({
          name: 'error-500'
        })
      }
      if (error.response.status === 404) {
        router.push({
          name: 'error-404'
        })
      }
    }
    return Promise.reject(error)
  }
)

let http = {
  post (url, data) {
    return new Promise(function (resolve, reject) {
      $http.post(url, { ...data, session_id: Cookies.get('session') }).then(
        res => {
          console.log(res)
          if (res.code && res.code != 500 && res.code != 10000) {
            resolve(res)
          }
        },
        res => {
          reject(res)
        }
      )
    })
  },
  baseUrl: api,
  baseHost: host
}
export default http



